﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HCEnvProxyServerTest
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			SendBroadcast();
			console.writeLine('123');
		}
		//例如: IP=192.168.1.10:4000, UPT=1, RepoAddr=9, 那么UDP的十六进制报文为:
		//C0 A8 01 0A 0F A0 01 09
		public static string SendBroadcast()
		{
			try
			{				
				using (Socket socks = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
				{
					int recv;
					StringBuilder builder = new StringBuilder();

					byte[] recvBytes = new byte[1024];
					//代理IP
					string ipValue = "127.0.0.1";
					//端口
					string port = "6100";
					//创建连接
					IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ipValue), int.Parse(port));
					EndPoint remote = (EndPoint)(iep);					
					byte[] myByteArray = new byte[] { 0xC0,0xA8,0x05,0x42,0x0F,0xA0,0x0b,0x01 };

					byte[] mmmm = GetIpUptAdd("192.168.5.66","11","1");
					socks.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
					socks.SendTo(mmmm, iep);
					recv = socks.ReceiveFrom(recvBytes, ref remote);

					if (recv > 8)
					{
						var floatlength = sizeof(float);
						var count = (recv - 8) / floatlength;

						for (int i = 1; i < count; i++)
						{
							float data = BitConverter.ToSingle(recvBytes, (i + 1) * 4);
							builder.Append(string.Format("{0},", data.ToString()));
						}
						socks.Dispose();
						int length = builder.ToString().Length;
						return builder.ToString().Substring(0, length - 1);
					}
					else//设备异常
					{
						socks.Dispose();
						return "fail";
					}

				}
			}
			catch { return "发送失败"; }
		}

		private static byte[] GetIpUptAdd(string ip, string upt, string add)
		{
					
			string[] ipStr = ip.Split('.');	
			
			byte[] myByteArray= new byte[8];
			myByteArray[0] = (byte)Int32.Parse(ipStr[0]);
			myByteArray[1] = (byte)Int32.Parse(ipStr[1]);
			myByteArray[2] = (byte)Int32.Parse(ipStr[2]);
			myByteArray[3] = (byte)Int32.Parse(ipStr[3]);
			//端口4000
			myByteArray[4] = 15;
			myByteArray[5] = 160;

			myByteArray[6] = (byte)Int32.Parse(upt);
			myByteArray[7] = (byte)Int32.Parse(add);

			return myByteArray;

		}
	}
}
